#include "logger.h"

//初始化静态成员
Logger* Logger::instance_ = nullptr;

void Logger::init(const std::string &filename, LogLevel level)
{
    if(instance_ == nullptr){
        instance_ = new Logger(filename, level);
    }
}

//获取单例
Logger& Logger::getInstance(){
    if(instance_ == nullptr){
        throw std::runtime_error("Logger not initialized");
    }
    return *instance_;
}

Logger::Logger(const std::string& filename, LogLevel level)
    :level_(level){
    file_.open(filename, std::ios::out | std::ios::app);
    if(!file_.is_open()){
        throw std::runtime_error("Cannot open log file:" + filename);
    }
}
void Logger::log(LogLevel level, const std::string& message){
    std::lock_guard<std::mutex> lock(getInstance().mutex_);
    if(level < getInstance().level_) return;
    std::string level_str;
    switch (level)
    {
        case LogLevel::DEBUG: 
            level_str = "DEBUG"; 
            break;
        case LogLevel::INFO:
            level_str = "INFO";
            break;
        case LogLevel::WARNING:
            level_str = "WARNING";
            break;
        case LogLevel::ERROR:
            level_str = "ERROR";
            break;
        default:
            break;
    }
    std::time_t now = std::time(nullptr);
    char timestamp[20];
    std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", std::localtime(&now));

    std::string log_entery = "[" + std::string(timestamp) + "] [" + level_str + "] " + message;
    getInstance().file_ <<log_entery<<std::endl;
    if(level >= LogLevel::ERROR){
        std::cerr<<log_entery <<std::endl;
    }
}

void Logger::debug(const std::string &message)
{
    log(LogLevel::DEBUG, message);
}

void Logger::info(const std::string &message)
{
    log(LogLevel::INFO, message);
}

void Logger::warning(const std::string &message)
{
    log(LogLevel::WARNING, message);
}

void Logger::error(const std::string &message)
{
    log(LogLevel::ERROR, message);
}
